//
//  MBDLoginViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/3/20.
//

import Foundation
import UIKit
import YYText
import SnapKit
import Alamofire
import SwiftyJSON
import Toast_Swift
import NVActivityIndicatorView

extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControl.State) {
        self.clipsToBounds = true  // add this to maintain corner radius
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
        }
    }
}


class MBDLoginViewController : MBDBaseViewController {
    var titleLabel : YYLabel!
    var tipsLabel : YYLabel!
    var phoneTextField : UITextField!
    var smsTextField : UITextField!
    var smsCodeButton : UIButton!
    var loginButton : UIButton!
    var confirmEULAButton : UIButton!
    var EULAButton : UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let titleAttributeString = NSMutableAttributedString(string: "手机验证登录")
        titleAttributeString.yy_font = UIFont.boldSystemFont(ofSize: 18)
        titleAttributeString.setDynamicTextColor()
        
        titleLabel = YYLabel()
        titleLabel.attributedText = titleAttributeString
        self.view.addSubview(titleLabel)
        
        phoneTextField = UITextField()
        phoneTextField.font = UIFont.systemFont(ofSize: 14)
        phoneTextField.keyboardType = UIKeyboardType.numberPad
        phoneTextField.borderStyle = UITextField.BorderStyle.roundedRect
        let phoneAttrStr = NSMutableAttributedString(string: "输入手机号码")
        phoneAttrStr.yy_font = UIFont.boldSystemFont(ofSize: 14)
        phoneAttrStr.setDynamicTextColor()
        
        phoneTextField.attributedPlaceholder = phoneAttrStr
        self.view.addSubview(phoneTextField)
        
        smsTextField = UITextField()
        smsTextField.font = UIFont.systemFont(ofSize: 14)
        smsTextField.borderStyle = UITextField.BorderStyle.roundedRect
        smsTextField.keyboardType = UIKeyboardType.numberPad
        let smsAttrStr = NSMutableAttributedString(string: "输入验证码")
        smsAttrStr.yy_font = UIFont.boldSystemFont(ofSize: 14)
        smsAttrStr.setDynamicTextColor()
        
        smsTextField.attributedPlaceholder = smsAttrStr
        self.view.addSubview(smsTextField)
        
        smsCodeButton = UIButton()
        smsCodeButton.setTitle("获取验证码", for: UIControl.State.normal)
        smsCodeButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        smsCodeButton.layer.cornerRadius = 18
        smsCodeButton.clipsToBounds = true
        smsCodeButton.backgroundColor = UIColor(colorHex: 0x4273d0)
        smsCodeButton.setBackgroundColor(color: UIColor(colorHex: 0x4273d0), forState: UIControl.State.normal)
        smsCodeButton.setBackgroundColor(color: UIColor(colorHex: 0x0951c6), forState: UIControl.State.highlighted)
        smsCodeButton.setBackgroundColor(color: UIColor.gray, forState: UIControl.State.disabled)

        smsCodeButton.addTarget(self, action: #selector(smsPressed), for: UIControl.Event.touchUpInside)
        smsCodeButton.setTitleColor(UIColor.white, for: UIControl.State.normal)
        smsCodeButton.titleLabel?.font=(UIFont.systemFont(ofSize: 14))
        self.view.addSubview(smsCodeButton)
        
        loginButton = UIButton()
        loginButton.setTitle("登录", for: UIControl.State.normal)
        loginButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        loginButton.layer.cornerRadius = 18
        loginButton.clipsToBounds = true
        loginButton.setBackgroundColor(color: UIColor(colorHex: 0x4273d0), forState: UIControl.State.normal)
        loginButton.setBackgroundColor(color: UIColor(colorHex: 0x0951c6), forState: UIControl.State.highlighted)
        loginButton.setBackgroundColor(color: UIColor.gray, forState: UIControl.State.disabled)

        loginButton.addTarget(self, action: #selector(loginPressed), for: UIControl.Event.touchUpInside)
        loginButton.setTitleColor(UIColor.white, for: UIControl.State.normal)
        loginButton.titleLabel?.font=(UIFont.systemFont(ofSize: 14))

        self.view.addSubview(loginButton)
        
        confirmEULAButton = UIButton()
        confirmEULAButton.setTitle(" 同意", for: UIControl.State.normal)
        confirmEULAButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        confirmEULAButton.setImage(UIImage(named: "ico_login_should_confirm"), for: .normal)
        confirmEULAButton.setImage(UIImage(named: "ico_login_did_confirm"), for: .selected)
        confirmEULAButton.addTarget(self, action: #selector(confirm), for: UIControl.Event.touchUpInside)
        confirmEULAButton.setTitleColor( ThemeManager.shared.dynamicTextColor(), for: UIControl.State.normal)

        self.loginButton.isEnabled = self.confirmEULAButton.isSelected

        self.view.addSubview(confirmEULAButton)
        
        EULAButton = UIButton()
        EULAButton.setTitle("用户协议", for: UIControl.State.normal)
        EULAButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        EULAButton.addTarget(self, action: #selector(lookEULA), for: UIControl.Event.touchUpInside)
        EULAButton.setTitleColor(UIColor(colorHex: 0x0000FF), for: UIControl.State.normal)
        self.view.addSubview(EULAButton)
        
        tipsLabel = YYLabel()
        tipsLabel.textColor = UIColor.red
        tipsLabel.font = UIFont.systemFont(ofSize: 14)
        self.view.addSubview(tipsLabel)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.centerX.equalTo(self.view)
        }
        
        phoneTextField.snp.makeConstraints { make in
            make.centerX.equalTo(self.view)
            make.top.equalTo(titleLabel.snp.bottom).offset(40)
            make.left.equalTo(40)
            make.height.equalTo(36)
        }
        
        smsTextField.snp.makeConstraints { make in
            make.left.equalTo(phoneTextField)
            make.width.equalTo(phoneTextField).offset(-118)
            make.top.equalTo(phoneTextField.snp.bottom).offset(15)
            make.height.equalTo(36)
        }
        
        smsCodeButton.snp.makeConstraints { make in
            make.top.equalTo(smsTextField)
            make.left.equalTo(smsTextField.snp.right).offset(10)
            make.right.equalTo(phoneTextField)
            make.height.equalTo(smsTextField)
        }
        
        loginButton.snp.makeConstraints { make in
            make.top.equalTo(smsTextField.snp.bottom).offset(15)
            make.centerX.equalTo(self.view)
            make.left.equalTo(phoneTextField)
            make.height.equalTo(36)
        }
        
        tipsLabel.snp.makeConstraints { make in
            make.top.equalTo(loginButton.snp.bottom).offset(10)
            make.left.equalTo(loginButton)
        }
        
        confirmEULAButton.snp.makeConstraints { make in
            make.top.equalTo(tipsLabel.snp.bottom).offset(15)
            make.left.equalTo(phoneTextField)
            make.height.equalTo(16)
            make.width.equalTo(44)
        }
        
        EULAButton.snp.makeConstraints { make in
            make.centerY.equalTo(confirmEULAButton)
            make.left.equalTo(confirmEULAButton.snp.right)
            make.height.equalTo(16)
            make.width.equalTo(77)
        }
        
        self.view.setDynamicBackgroundColor()

    }
    
    override func updateColors() {
        super.updateColors()
    }
    
    @objc func confirm() {
        self.confirmEULAButton.isSelected = !self.confirmEULAButton.isSelected
        self.loginButton.isEnabled = self.confirmEULAButton.isSelected
    }
    
    @objc func lookEULA() {
        let vc = MBDEULAViewController()
        self.showDetailViewController(vc, sender: self)
    }
    
    
    @objc func loginPressed() {
        let phoneIsBlank = phoneTextField.text == nil || phoneTextField.text!.isBlank
        if  (phoneIsBlank) {
            tipsLabel.text = "请输入手机号码"
            return
        }
        
        let validPhone = validatedPhone(phoneStr: phoneTextField.text!)
        if  (!validPhone) {
            tipsLabel.text = "手机号码不正确"
            return
        }
        
        let smsIsBlank = smsTextField.text == nil || smsTextField.text!.isBlank
        if  (smsIsBlank) {
            tipsLabel.text = "请输入验证码"
            return
        }
        
        tipsLabel.text = ""
        
        let params = ["phoneNumber":phoneTextField.text,"verificationCode":smsTextField.text]
        
        self.startIndicatorAnimating()
        MBDHttpClient.shared.doPostRequest("/user/login",parameters: params).httpClientResponse { error, response in
            self.stopIndicatorAnimationg()
            if nil != error {
                self.view.makeToast(error?.localizedDescription,position: .center)
            } else {
                
                if let rawDict = response?.rawDict {
                    
                    if let data = rawDict["data"]  {
                        MBDUserCenter.shared.token = data as! String
                        self.view.makeToast("登录成功！")                        

                    } else {
                        self.view.makeToast("登录失败！")
                    }
                }
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    // your code here
                    self.dismiss(animated: true)
                }
            }
            
        }

    }
    
    
    /// 多少秒后按钮可用
    /// - Parameter time: 秒数
    private func smsButtonEnableAfter(time : Int){
        if(time < 1) {
            smsCodeButton .setTitle("获取验证码", for: UIControl.State.normal)
            smsCodeButton.isEnabled = true
            return
        }
        
        self.smsCodeButton.isEnabled = false
        smsCodeButton.setTitle(time.description.appending(" s"), for: UIControl.State.normal)
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            // your code here
            self.smsButtonEnableAfter(time: time - 1)
        }
        
    }
    
    @objc func smsPressed() {
        let phoneIsBlank = phoneTextField.text == nil || phoneTextField.text!.isBlank
        if  (phoneIsBlank) {
            tipsLabel.text = "请输入手机号码"
            return
        }
        
        let validPhone = validatedPhone(phoneStr: phoneTextField.text!)
        if  (!validPhone) {
            tipsLabel.text = "手机号码不正确"
            return
        }
        tipsLabel.text = ""
        
        self.smsButtonEnableAfter(time: 30)
        self.startIndicatorAnimating()

        let para = ["phoneNumber":phoneTextField.text!]
        MBDHttpClient.shared.doPostRequest("/user/send/verificationCode",parameters: para).httpClientResponse { error, response in
            self.stopIndicatorAnimationg()

            if nil != error {
                self.view.makeToast(error?.localizedDescription)
            } else {
                self.view.makeToast("验证码获取成功！")
            }
        }
        
    }
    
    /// 将颜色转换为图片
    ///
    /// - Parameter color: UIColor
    /// - Returns: UIImage
    func imageFromColor(color: UIColor, viewSize: CGSize) -> UIImage {
        let rect: CGRect = CGRect(x: 0, y: 0, width: viewSize.width, height: viewSize.height)
        
        UIGraphicsBeginImageContext(rect.size)
        
        let context: CGContext = UIGraphicsGetCurrentContext()!
        context.setFillColor(color.cgColor)
        context.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsGetCurrentContext()
        return image!
    }
    
    func validatedPhone(phoneStr: String) -> Bool {
        let phone = phoneStr.trimmingCharacters(in: CharacterSet.whitespaces)
        let regex = "^1\\d{10}$"
        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
        let result = predicate.evaluate(with: phone)
        return result
    }
}

